#include "ServerNetworkManager.h"
#include <assert.h>
#include "Packet.h"
#include <iostream>
ServerNetworkManager::ServerNetworkManager(void)
	:
	m_listenThread(INVALID_HANDLE_VALUE),
	m_clientSocket(INVALID_SOCKET)
{
	Init();
}
ServerNetworkManager::~ServerNetworkManager(void)
{
	Shutdown();
}
void ServerNetworkManager::Init(void)
{
	sockaddr_in addr = {0};
	addr.sin_addr.S_un.S_addr = INADDR_ANY;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(SERVER_PORT);
	int ret = bind(m_socket, (sockaddr*)&addr, sizeof(addr));
	assert(!ret);

	m_isRunning = true;
	CreateThread(0, 0, (LPTHREAD_START_ROUTINE)ListenThread, this, 0, 0);
} 
void ServerNetworkManager::Shutdown(void)
{
	//NetworkManager::Shutdown();
	m_isRunning = false;
}
void ServerNetworkManager::SendToClient(Packet* packet)
{
	SendPacket(packet, m_clientSocket);
}
void ServerNetworkManager::ListenThread(ServerNetworkManager& mgr)
{
	while (mgr.IsRunning())
	{
		int ret = listen(mgr.m_socket, SOMAXCONN);

		if (ret != SOCKET_ERROR)
		{
			SOCKET client = accept(mgr.m_socket, 0, 0);
			mgr.m_clientSocket = client;
			RecvThreadArgs* args = new RecvThreadArgs();
			args->mgr = &mgr;
			args->socket = client;
			CreateThread(0, 0, (LPTHREAD_START_ROUTINE)SocketRecvThread, args, 0, 0);
		}
	}
}
bool ServerNetworkManager::ClientConnected(void)
{
	bool test = m_clientSocket != INVALID_SOCKET;
	return m_clientSocket != INVALID_SOCKET;
}